<template>
  <el-dialog :model-value="visible" :title="questionId ? '编辑问题' : '我要提问'" width="650px" @close="onCancel">
    <div class="dialog-form">
      <div class="form-row">
        <span class="form-label required">标题</span>
        <el-input v-model="title" class="form-input" placeholder="请输入标题" />
      </div>
      <div class="form-row">
        <span class="form-label required">专业领域</span>
        <el-tree-select v-model="specialtyTagIds" class="form-input" :data="specialtyTagList" multiple filterable
          clearable check-strictly placeholder="请选择专业领域" :props="{
            value: 'id',
            label: 'tagName',
            children: 'children'
          }" />
      </div>
      <div class="form-row" v-if="!type">
        <span class="form-label">指定专家</span>
        <el-select 
        placeholder="请搜索指定专家"
        remote
        :remote-method="remoteMethod"
        :loading="loading"
        v-model="uidList" multiple filterable clearable :disabled="questionId?true:false">
          <el-option v-for="item in expertList" :key="item.value" :label="item.label" :value="item.value">
            <div class="flex items-center">
              <el-avatar :src="item.avatar" style="margin-right: 8px" :size="24" />
              <span>{{ item.label }}</span>
            </div>
          </el-option>
          <!-- <template #tag>
            <el-tag v-for="color in value" :key="color" :color="color" />
          </template> -->
        </el-select>
      </div>
      <!-- <div class="form-row">
        <span class="form-label">讨论区</span>
        <SubmitSelectTopic :onTopicClick="handleTopicClick" />
        <SubmitSelectDiscuss
            v-if="topicId"
            :selectedDiscussName="selectedDiscussName"
            :onDiscussClick="handleDiscussClick"
            :topicId="topicId" />
      </div> -->
      <div class="form-row">
        <span class="form-label required">内容</span>
        <RichTextEditor v-model="content" class="form-input" />
      </div>
      <!-- <div class="form-row">
        <span class="form-label">封面</span>
        <LfImageUpload ref="coverUploadRef" :maxCount="1" title="上传封面" class="form-input" />
      </div> -->
      <div class="form-row">
        <span class="form-label">期望解答时间（天）</span>
        <el-input v-model="expectedTime" class="form-input" placeholder="请输入期望解答天数" type="number" min="1" :max="365"
          style="width: 200px" />
      </div>
    </div>
    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { defineProps, defineEmits, ref, onMounted, watch } from 'vue'
import LfInput from '@/components/commonUI/LfInput.vue'
import LfImageUpload from '@/components/commonUI/LfImageUpload.vue'
import RichTextEditor from './RichTextEditor.vue'
import SubmitSelectDiscuss from './SubmitSelectDiscuss.vue'
import { ElTreeSelect, ElButton, ElDialog, ElSelect, ElOption, ElMessage, ElInput, ElAvatar } from 'element-plus'
import SubmitSelectTopic from "@/views/Submit/components/SubmitSelectTopic.vue";
import { getSpecialtyTagTree, getQuestionInfo, postCreateQuestion, updateQuestion } from '@/axios/api/question'
import { getExpertList } from '@/axios/api/expert'
import { useGlobalStore } from '@/stores/globalStore'
const globalStore = useGlobalStore()

const props = defineProps({
  visible: Boolean,
  questionId: {
    type: [String, Number],
    default: ''
  },
  type: String || Number || null,
  uid: String || Number || null,
})
const emit = defineEmits(['close', 'success', 'update:visible'])
const expectedTime = ref('')
const title = ref('')
const specialtyTagIds = ref([])
const specialtyTagList = ref([])
const questionTypeList = [
  { value: 'general', label: '常规问题' },
  { value: 'urgent', label: '紧急问题' },
  { value: 'suggestion', label: '建议' },
]
const content = ref('')
const coverUploadRef = ref(null)

const selectedDiscussName = ref('')
const selectedDiscussId = ref(null)


const uidList = ref([])
const expertList = ref([])
const loading = ref(false)
const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    // setTimeout(() => {
    //   loading.value = false
    //   expertList.value = list.value.filter((item) => {
    //     return item.label.toLowerCase().includes(query.toLowerCase())
    //   })
    // }, 200)
    getExpertListData(query)
  } else {
    expertList.value = []
  }
}

// 获取专家列表
const getExpertListData = async (name='') => {
  try {
    const res = await getExpertList({ keyword: name, limit: 10, page: 1 })
    if (res.code === 0) {
      expertList.value = res.data.list.map(item => ({
        value: item.uid,
        label: item.name,
        avatar: item.avatar
      }))
      loading.value = false
      
    }
  } catch (error) {
    console.error('获取专家列表失败:', error)
    ElMessage.error('获取专家列表失败')
  }
}

const handleInputChange = (e) => {
  title.value = e.target.value
}
const handleDiscussClick = (id, name) => {
  selectedDiscussId.value = id
  selectedDiscussName.value = name
}

const handleTopicClick = (id, name) => {
  topicId.value = id
  // 清除讨论
  selectedDiscussId.value = undefined
  selectedDiscussName.value = undefined
}

const resetForm = () => {
  title.value = ''
  specialtyTagIds.value = []
  uidList.value = []
  content.value = ''
  expectedTime.value = ''
}

const onCancel = () => {
  globalStore.setIsShowQuestionDialog(false)
  resetForm()
  emit('update:visible', false)
}

const verify = () => {
  if (!title.value?.trim()) {
    ElMessage.error('请输入标题')
    return false
  }
  if (!specialtyTagIds.value?.length) {
    ElMessage.error('请选择专业领域')
    return false
  }
  if (!content.value?.trim()) {
    ElMessage.error('请输入内容')
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (!verify()) return
  if(expectedTime.value>(365*3)) {
    ElMessage.error('期望解答时间最大不能超过365*3天')
    return false
  }

  const params = {
    title: title.value.trim(),
    specialtyTagIds: specialtyTagIds.value,
    content: content.value.trim(),
    expectedTime: expectedTime.value || 0,
    uidList: uidList.value
  }
  if (props.questionId) {
    params.id = props.questionId
  }
  if (props.uid) {
    params.uidList = [props.uid]  
  }

  const api = props.questionId ? updateQuestion : postCreateQuestion
  try {
    const res = await api(params)
    if (res.code === 0) {
      globalStore.setIsShowQuestionDialog(false)
      ElMessage.success('提交成功')
      emit('success', res.data)
      emit('update:visible', false)
      resetForm()
    } else {
      ElMessage.error(res.msg || '提交失败')
    }
  } catch (error) {
    console.error('提交问题失败:', error)
    // ElMessage.error('提交失败，请稍后重试')
  }
}

// 获取专业领域标签树
const getSpecialtyTagList = async () => {
  try {
    const res = await getSpecialtyTagTree()
    if (res.code === 0) {
      specialtyTagList.value = res.data
    }
  } catch (error) {
    console.error('获取专业领域标签失败:', error)
    ElMessage.error('获取专业领域失败')
  }
}

// 获取问题详情
const getQuestionDetail = async (id) => {
  try {
    const res = await getQuestionInfo(id)
    if (res.code === 0) {
      const { title: questionTitle, content: questionContent, expectedTime: questionExpectedTime, specialtyTagIds: questionTagIds,expertList: questionExpertList } = res.data

      let datas = questionExpertList || []
      title.value = questionTitle
      content.value = questionContent
      expectedTime.value = questionExpectedTime
      uidList.value = datas.map(item => item.uid)
      
      expertList.value = datas.map(item => ({
        value: item.uid,
        label: item.username,
        // avatar: item.avatar
      }))

      console.log( expertList.value);
      
      let data = questionTagIds.length ? questionTagIds.split(',').map(id => id) : []
      // let data = questionTagIds.length ? questionTagIds.split(',').map(id => parseInt(id.trim())) : []
      specialtyTagIds.value = data
    }
  } catch (error) {
    console.error('获取问题详情失败:', error)
    ElMessage.error(error)
  }
}

// 监听对话框关闭，确保关闭时重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    resetForm()
  } else if (props.questionId) {
    getQuestionDetail(props.questionId)
  }
})

onMounted(() => {
  getSpecialtyTagList()
  getExpertListData()
})
</script>
<style scoped>
.dialog-form {
  display: flex;
  flex-direction: column;
  gap: 18px;
  /* height: 500px; */
  overflow-y: auto;
  padding-right: 10px;
}

.form-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.form-label {
  width: 70px;
  color: #333;
  font-weight: 500;
  flex-shrink: 0;
  margin-top: 6px;
}

.form-label.required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.form-input {
  flex: 1;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}
</style>
